
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter/first/ui/page_register.dart';
import 'package:toast/toast.dart';

import '../app_manager.dart';
import '../event/events.dart';
import '../http/Api.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String? _userName, _password;
  final _formKey = GlobalKey<FormState>();
  FocusNode _pwdNode = FocusNode();
  bool _isObscure = true;
  Color _pwdIconColor = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        leading: InkWell(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(Icons.arrow_back,color: Colors.white),
        ),
        title: Text("登录",style: TextStyle(color: Colors.white)),
      ),

      body: Form(
        key: _formKey,
        //表单
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 22.0),
          children: [
            _buildUserName(),
            _buildPwd(),
            _buildLogin(),
            _buildRegister(),
          ],
        ),
      ),
    );
  }

  Widget _buildRegister() {
    return Padding(
      padding: EdgeInsets.only(top: 10.0),
      child: Row(
        ///孩子居中对齐
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('没有账号？'),
          GestureDetector(
            child: Text('点击注册', style: TextStyle(color: Colors.green)),
            onTap: () async {
              ///进入注册
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) {
                    return RegisterPage();
                  },
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildLogin() {
    return Container(
      height: 45.0,
      margin: EdgeInsets.only(top: 18.0, left: 8.0, right: 8.0),
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: WidgetStateProperty.all(Colors.blue),
        ),
        onPressed: () => _doLogin(),
        child: Text(
          '登录',
          style: TextStyle(fontSize: 18.0, color: Colors.white),
        ),
      ),
    );
  }

  Widget _buildPwd() {
    return TextFormField(
      focusNode: _pwdNode,
      obscureText: _isObscure,
      validator: (String? value) {
        if (value == null || value.trim().isEmpty) {
          return '请输入密码';
        }
        _password = value;
        return null;
      },
      textInputAction: TextInputAction.done,
      onEditingComplete: _doLogin,
      decoration: InputDecoration(
        labelText: '密码',

        suffixIcon: IconButton(
          icon: Icon(Icons.remove_red_eye, color: _pwdIconColor),
          onPressed: () {
            setState(() {
              _isObscure = !_isObscure;
              _pwdIconColor = (_isObscure
                  ? Colors.blue
                  : Theme.of(context).iconTheme.color)!;
            });
          },
        ),
      ),
    );
  }

  Widget _buildUserName() {
    return TextFormField(
      autofocus: true,  //提供默认焦点
      decoration: InputDecoration(labelText: '用户名'),
      textInputAction: TextInputAction.next,
      //按下键盘动作的响应
      onEditingComplete: () {
        FocusScope.of(context).requestFocus(_pwdNode);
      },
      validator: (String? value) {
        if (value == null || value.trim().isEmpty) {
          return '请输入用户名';
        }
        _userName = value;
        return null; //null表示验证通过
      },
    );
  }

  void _doLogin() async {
    _pwdNode.unfocus();

    if (_formKey.currentState!.validate()) {
      showDialog(context: context,barrierDismissible: false,builder: (_){
        return Center(child: CircularProgressIndicator(),);
      });

      var result = await Api.login(_userName!, _password!);
      Navigator.pop(context);
      if (result['errorCode'] == -1) {
        Toast.show(result['errorMsg'], gravity: Toast.bottom);
      } else {
        AppManager.prefs?.setString(AppManager.USER_NAME, _userName!);
        AppManager.prefs?.setString(AppManager.USER_PASSWORD, _password!);
        AppManager.prefs?.setBool(AppManager.LOGIN_STATE, true);
        AppManager.eventBus.fire(LoginEvent(_userName!, _password!));
        AppManager.isLogin = true;
        Navigator.pop(context);
      }
    }
  }
}
